package com.example.demo_bitmap

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    private lateinit var iv1: ImageView
    private lateinit var iv2: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        iv1 = findViewById(R.id.iv1)
        iv2 = findViewById(R.id.iv2)
        test1()
        //尺寸压缩/二次采样 一张图片100*100显示在很小ImageView10*10上，照片墙
        test2()
    }

    private fun test2() {
        //第一次：不采集像素点，只采集图片宽度和高度
        val option = BitmapFactory.Options()
        option.inPreferredConfig = Bitmap.Config.RGB_565
        option.inJustDecodeBounds = true //只采边框,不采像素点
        BitmapFactory.decodeResource(resources, R.drawable.a, option)
        Log.d("MainActivity", "宽度:${option.outWidth} ")
        Log.d("MainActivity", "高度:${option.outHeight} ")
        //第二次：计算压缩比例，按照压缩比例采集像素点，减少内存开销
        var size = 1 //压缩比例必须2的幂次方
        while (option.outWidth / size > 200 || option.outHeight / size > 200){ //100dp转px
            size *= 2
        }
        option.inSampleSize = size
        option.inJustDecodeBounds = false //采像素点
        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.a, option)
        Log.d("MainActivity", "二次采样后的大小:${bitmap.byteCount} ")
        iv2.setImageBitmap(bitmap)
        bitmap.recycle()
    }

    private fun test1() {
        //参数
        val option = BitmapFactory.Options()
        option.inPreferredConfig = Bitmap.Config.RGB_565     //编码格式RGB565
        //加载图片
        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.a,option)
        Log.d("MainActivity", "RGB_565宽度: ${bitmap.width}")
        Log.d("MainActivity", "RGB_565高度: ${bitmap.height}")
        Log.d("MainActivity", "RGB_565大小: ${bitmap.byteCount}")

        option.inPreferredConfig = Bitmap.Config.ARGB_8888 //编码格式ARGB_8888
        val bitmap2 = BitmapFactory.decodeResource(resources, R.drawable.a,option)
        Log.d("MainActivity", "ARGB_8888: ${bitmap.width}")
        Log.d("MainActivity", "ARGB_8888: ${bitmap.height}")
        Log.d("MainActivity", "ARGB_8888: ${bitmap2.byteCount}")

        iv1.setImageBitmap(bitmap)
        bitmap.recycle()
        bitmap2.recycle()
    }
}